﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using Volo.Abp;
using XfTech.SmartTms.Entities.Issues;
using Volo.Abp.Identity;

namespace XfTech.SmartTms.DomainServices
{
    /// <summary>
    /// 问题管理（领域服务）
    /// </summary>
    public class IssueManager : DomainService
    {
        private readonly IRepository<Issue, Guid> _issueRepository;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="issueRepository"></param>
        public IssueManager(IRepository<Issue, Guid> issueRepository)
        {
            _issueRepository = issueRepository;
        }

        /// <summary>
        /// 给问题分配负责人
        /// </summary>
        /// <param name="issue"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        public async Task AssignToAsync(Issue issue, IdentityUser user)
        {
            //判断如果该负责人已经有三个以上打开的问题，则提示 业务异常信息
            var openIssueCount = await _issueRepository.CountAsync(
                i => i.AssignedUserId == user.Id && !i.IsClosed
            );

            if (openIssueCount >= 3)
            {
                throw new BusinessException("IssueTracking:ConcurrentOpenIssueLimit");
            }

            issue.AssignedUserId = user.Id;
        }
    }

}
